<template>
  <el-main>
    <div>
      <el-tabs
        class="tabHight"
        :tab-position="tabPosition"
        v-model="siteTabs"
        @tab-click="invalidateMap"
      >
        <el-tab-pane label="详情" name="first">
          <!-- from表单 -->
          <el-form
            class="tabHight_auto"
            :model="editAreaEntiry"
            :rules="rules"
            ref="editAreaEntiry"
            label-width="auto"
            size="mini"
          >
            <el-form-item label="Token:" prop="token">
              <el-input
                v-model="editAreaEntiry.token"
                disabled
                placeholder="请输入2-30字符标识符"
              ></el-input>
            </el-form-item>
            <el-form-item label="名称:" prop="name">
              <el-input
                v-model="editAreaEntiry.name"
                placeholder="请输入15字符以内名称"
              ></el-input>
            </el-form-item>
            <!-- 站点类型下拉 -->
            <el-form-item label="站点类型:" prop="areaType">
              <el-select
                class="w100"
                v-model="editAreaEntiry.areaType"
                placeholder="请选择站点类型"
              >
                <el-option
                  v-for="item in areaTypeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.token"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="图像:" prop="imageUrl">
              <div style="width: 100%">
                <el-row>
                  <el-col :span="6">
                    <app-upload
                      tips=""
                      :is-resolution="true"
                      :width="720"
                      :height="294"
                      @subUploadSucceed="handleUploadSucceed"
                    />
                  </el-col>
                  <el-col :span="18">
                    <div class="imageHome" v-if="showImg">
                      <img
                        v-if="editAreaEntiry.imageUrl"
                        :src="editAreaEntiry.imageUrl | filtersFileUrl()"
                        class="image-size"
                      />
                    </div>
                  </el-col>
                </el-row>
              </div>
            </el-form-item>

            <el-form-item label="描述:" prop="description">
              <el-input
                type="textarea"
                v-model="editAreaEntiry.description"
                placeholder="请输入描述"
              ></el-input>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <!-- 边界样式 -->
        <el-tab-pane label="边界" name="second">
          <div id="mapSite"></div>
        </el-tab-pane>
        <!-- 元数据样式 -->
        <el-tab-pane label="元数据" name="third">
          <metaData
            :editmetaData="editmetaData"
            :isedit="isedit"
            @sendmetaDatas="sendmetaData"
          />
        </el-tab-pane>
      </el-tabs>
      <el-divider style="color: #000000"></el-divider>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialog" size="mini">取 消</el-button>
        <el-button
          type="primary"
          @click="submitForm('editAreaEntiry')"
          size="mini"
          :loading="btnLoading"
          v-permission="[3, 'button']"
          >确 定</el-button
        >
      </span>
    </div>
  </el-main>
</template>

<script>
import metaData from "../opensite/metaData";
import AppUpload from "../device/devicegroups/UploadImage.vue";
import "../../styles/uploadImg.sass";
import {
  initMap,
  addControlOptions,
  createIcon,
} from "../../utils/leaflet-map";
import icon from "@/icons/comm/marker-icon-2x-violet.png";
import { TOKEN_RULES } from "@/utils/local";
import { getAreatypes, getAreas, putAreatypes } from "@/api/superlinkAreat";
export default {
  components: {
    // coverDatatab,
    metaData,
    AppUpload,
  },
  props: {},
  data() {
    return {
      btnLoading: false,
      tabPosition: "left",
      map: "",
      layer: "",
      isedit: true,
      siteTabs: "first",
      rules: {
        token: TOKEN_RULES,
        name: [
          { required: true, message: "请输入名称", trigger: "blur" },
          { min: 2, max: 15, message: "输入格式不正确", trigger: "blur" },
        ],
        imageUrl: [{ required: true, message: "请上传图片", trigger: "blur" }],
        areaType: [
          {
            required: true,
            message: "请选择站点类型",
            trigger: ["blur", "change"],
          },
        ],
      },
      areaTypeList: "",
      areaToken: this.$route.query.areaToken,
      editAreaEntiry: {
        token: "",
        name: "",
        areaType: "",
        imageUrl: "",
        description: "",
      },
      // editcoverData: [],
      editmetaData: [],
      // coverDataSelectedIds: [],
      metaDataJson: {},
      editBounds: [], //经纬度
      mapEdit: [], //转换后数据
    };
  },
  mounted() {
    this.areaByToken();
    this.AreaTypes();
  },
  computed: {
    showImg: function () {
      return this.editAreaEntiry.imageUrl != "";
    },
  },
  methods: {
    // 图片上传
    handleUploadSucceed(url) {
      this.editAreaEntiry.imageUrl = url;
    },
    editdialog() {
      this.$emit("closeeditdialog", false);
      // this.editAreaEntiry = {
      //   token: "",
      //   name: "",
      //   areaType: "",
      //   imageUrl: "",
      //   description: "",
      // };
      // this.map.remove(),
      // this.layer = [],
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let formData = {};
          formData.areaTypeToken = this.editAreaEntiry.areaType;
          formData.description = this.editAreaEntiry.description;
          formData.imageUrl = this.editAreaEntiry.imageUrl;
          formData.metadata = this.metaDataJson;
          formData.name = this.editAreaEntiry.name;
          formData.token = this.editAreaEntiry.token;
          formData.bounds = this.editBounds;
          this.btnLoading = true;
          putAreatypes(formData, this.areaToken)
            .then((res) => {
              this.$msg({
                type: "success",
                message: "操作成功!",
              });
              this.$emit("submitForm", false, this.editAreaEntiry.token);
            })
            .finally((f) => {
              this.btnLoading = false;
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    // 初始化地图
    load_Map_2() {
      console.log(L, "LLLLLLLLLLLLLLLLLL");
      var that = this;
      var latlng = "";
      if (JSON.stringify(that.editBounds) != "[]" || that.editBounds[0]) {
        latlng = {
          lat: that.editBounds[0].latitude,
          lng: that.editBounds[0].longitude,
        };
      }
      var map = initMap("mapSite", latlng, 5);
      // addControlOptions(map, [
      //   "drawRectangle",
      //   "drawPolygon",
      //   "removalMode",
      //   "enable",
      //   "editMode",
      // ]);
      const options = [
        "drawRectangle",
        "drawPolygon",
        "removalMode",
        "enable",
        "editMode",
      ];
      map.pm.addControls({
        position: "topleft",
        drawPolygon: options.includes("drawPolygon"), // 添加绘制多边形
        drawMarker: options.includes("drawMarker"), //添加按钮以绘制标记
        drawCircleMarker: options.includes("drawCircleMarker"), //添加按钮以绘制圆形标记
        drawPolyline: options.includes("drawPolyline"), //添加按钮绘制线条
        drawRectangle: options.includes("drawRectangle"), //添加按钮绘制矩形
        drawCircle: options.includes("drawCircle"), //  添加按钮绘制圆圈
        editMode: options.includes("editMode"), //  添加按钮编辑多边形
        dragMode: options.includes("dragMode"), //   添加按钮拖动多边形
        cutPolygon: options.includes("cutPolygon"), // 添加一个按钮以删除图层里面的部分内容
        removalMode: options.includes("removalMode"), // 清除图层
      });

      // 设置绘制后的线条颜色等
      map.pm.setPathOptions({
        color: "orange",
        fillColor: "green",
        fillOpacity: 0.4,
      });
      map.pm.setLang("zh"); //设置语言  en, de, it, ru, ro, es, fr, pt_br, zh , nl

      if (that.editBounds != "{}") {
        // 转换数据格式
        var mapEdit1 = [];
        let ele = {};
        that.editBounds.forEach((item) => {
          var itemList = [item.latitude, item.longitude];
          mapEdit1.push(itemList);
        });
        var myIcon = createIcon(icon);
        that.layer = L.polygon(mapEdit1, {
          draggable: false,
          icon: myIcon,
        }).addTo(map);
        that.layer.on("pm:edit", (e) => {
          that.editBounds = [];
          let mapeditlist = that.layer._latlngs;
          let ele = {};
          mapeditlist[0].forEach((item) => {
            ele = {
              latitude: item.lat,
              longitude: item.lng,
            };
            that.editBounds.push(ele);
          });
          // that.editBounds = that.layer._latlngs;
          console.log("编辑区域", e);
        });
      }

      map.on("pm:create", (e) => {
        if (that.layer) {
          map.removeLayer(that.layer); // 移除已有图层,限制只有一个marker
        }

        // 清空参数，只保留当前
        that.editBounds = [];
        // 转换数据格式
        that.layer = e.layer;
        let maplist = e.layer._latlngs;
        let ele = {};
        maplist[0].forEach((item) => {
          ele = {
            latitude: item.lat,
            longitude: item.lng,
          };
          that.editBounds.push(ele);
        });

        console.log("划区域", e);
      });
      // 站点地图编辑内删除区域
      map.on("pm:remove", (e) => {
        that.editBounds = [];
      });
      that.map = map;
    },

    // 下拉框选择站点类型
    AreaTypes() {
      var param = { includeContainedAreaTypes: false, page: 1, pageSize: 100 };
      getAreatypes(param).then((res) => {
        this.areaTypeList = res.data.results;
      });
    },
    // 获取详情
    areaByToken() {
      var that = this;
      var param = { includeContainedAreaTypes: true };
      getAreas(param, this.areaToken).then((res) => {
        const r = res.data;
        that.editAreaEntiry = Object.assign({}, r);
        that.editAreaEntiry.areaType = r.areaType.name;
        that.editmetaData = r.metadata;
        if (r.bounds) {
          that.editBounds = r.bounds;
        }
        that.metaDataJson = that.editAreaEntiry.metadata;

        that.load_Map_2();
      });
    },

    //元数据页回传
    sendmetaData(md) {
      this.metaDataJson = md;
    },

    //地图重新调整位置
    invalidateMap(tab) {
      if (tab.name == "second") {
        this.$nextTick(() => {
          this.map.invalidateSize(true);
        });
      }
    },
  },
};
</script>

<style scoped>
.dialog-footer {
  float: right;
}
#mapSite {
  width: 100%;
  z-index: 1;
  overflow: hidden;
  height: 55vh;
}
</style>>
